//
//  ErrorCorrectionViewController.m
//  AI
//
//  Created by zjhc on 2018/2/6.
//  Copyright © 2018年 zjhc. All rights reserved.
//

#import "ErrorCorrectionViewController.h"
#import "SaveCorrectionResultViewController.h"
#import "AudioStreamer.h"
#import "WTAudioObject.h"
#import <SVProgressHUD.h>

@class AudioStreamer;

@interface ErrorCorrectionViewController (){
    AudioStreamer *streamer;
}

@end

@implementation ErrorCorrectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.contentTextView.text = self.record.content;
    self.updateContentStackView.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:@"saveCorrectionSegue"]) {
        SaveCorrectionResultViewController *saveCorrectionVC = segue.destinationViewController;
        saveCorrectionVC.record = self.record;
    }
}

#pragma mark - 播放录音

- (IBAction)playRecord:(id)sender {
    
    UIButton *btn = (UIButton *)sender;
    
    if ([self.record.filePath localizedCaseInsensitiveContainsString:@"wav"]) {
        [self onlinePlay:btn];
    } else if ([self.record.filePath localizedCaseInsensitiveContainsString:@"pcm"]){
        [self offlinePlay:btn];
    } else {
        [SVProgressHUD showErrorWithStatus:@"该播放格式不支持"];
    }
}

#pragma mark - 在线播放
-(void)onlinePlay:(UIButton *)btn {
    if (btn.selected) {
        [self createStreamer];
        [streamer start];
        [btn setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        self.statusTip.text = @"暂停";
        btn.selected = !btn.selected;
    } else {
        [streamer stop];
        [btn setBackgroundImage:[UIImage imageNamed:@"playAudio"] forState:UIControlStateNormal];
        self.statusTip.text = @"点击播放语音";
        btn.selected = !btn.selected;
    }
}
#pragma mark - 离线播放
-(void)offlinePlay:(UIButton *)btn {
    
    
    if (btn.selected) {
//        [[WTAudioObject shareInstance] playAudioWithPath:@""];
        [self downloadAudioFile];
        [btn setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        self.statusTip.text = @"暂停";
        btn.selected = !btn.selected;
    } else {
        [[WTAudioObject shareInstance] stopAudio];
        [btn setBackgroundImage:[UIImage imageNamed:@"playAudio"] forState:UIControlStateNormal];
        self.statusTip.text = @"点击播放语音";
        btn.selected = !btn.selected;
    }
}

-(void)downloadAudioFile {
    
    // 创建下载路径
    NSURL *url = [NSURL URLWithString:self.record.filePath];
    
    // 创建NSURLSession对象，并设计代理方法。其中NSURLSessionConfiguration为默认配置
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // 创建任务
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
    
    // 开始任务
    [downloadTask resume];
}



- (IBAction)errorCorrection:(id)sender {
    [self performSegueWithIdentifier:@"saveCorrectionSegue" sender:sender];
}

#pragma mark - 其它页面点击返回按钮，然后返回至登录页面的钩函数，可以传值
- (IBAction)unwindToErrorCorrectionVC:(UIStoryboardSegue*)sender
{
    SaveCorrectionResultViewController *sourceViewController = sender.sourceViewController;
    self.updateContentTextView.text = sourceViewController.record.update_content;
}

-(void)viewWillAppear:(BOOL)animated {
    
    if ([self.record.update_content isEqualToString:@""]||self.record.update_content == nil) {
        self.updateContentStackView.hidden = YES;
    } else {
        self.updateContentStackView.hidden = NO;
        self.updateContentTextView.text = self.record.update_content;
    }
    self.tabBarController.tabBar.hidden = YES;
}

//
// destroyStreamer
//
// Removes the streamer, the UI update timer and the change notification
//
- (void)destroyStreamer
{
    if (streamer)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:streamer];
        [streamer stop];
        streamer = nil;
        
    }
}

// createStreamer
//
// Creates or recreates the AudioStreamer object.
//
- (void)createStreamer
{
    if (streamer)
    {
        return;
    }
    [self destroyStreamer];
    
    NSURL *url = [NSURL URLWithString:self.record.filePath];
    streamer = [[AudioStreamer alloc] initWithURL:url];
    
}

void getFileName(NSString* urlString) {
    //1、lastPathComponent
    NSString *fileName = [urlString lastPathComponent];
    NSLog(@"1、lastPathComponent\n%@", fileName);
    //2、pathComponents
    NSArray *urlComponentArray = [urlString pathComponents];
    NSLog(@"2、pathComponents\n%@", [urlComponentArray lastObject]);
    //3、componentsSeparatedByString字符串分割法
    NSArray *urlSeparatedStr = [urlString componentsSeparatedByString:@"/"];
    NSLog(@"3、componentsSeparatedByString\n%@", [urlSeparatedStr lastObject]);
    //4、NSRange尾部截取法
    NSRange range = [urlString rangeOfString:@"/"options:(NSBackwardsSearch)];
    if(range.location ==NSNotFound) {
        fileName = urlString;
    } else {
        fileName = [urlString substringFromIndex:range.location+1];
    }
    NSLog(@"4、NSRange\n%@", fileName);
}

#pragma mark <NSURLSessionDownloadDelegate> 实现方法
/**
 *  文件下载完毕时调用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location{
    
    NSError *saveError;
    
    NSString *downloadFileName = [self.record.filePath lastPathComponent];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
   
     NSString * savePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",downloadFileName]];
    
    NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
    
    //把下载的内容从cache复制到document下
    
    [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
    
    if (!saveError) {
        [SVProgressHUD showSuccessWithStatus:@"下载成功"];
        [[WTAudioObject shareInstance] playAudioWithPath:savePath];
    }else{
        
        if (saveError.code == 516) {
            [[WTAudioObject shareInstance] playAudioWithPath:savePath];
//            [SVProgressHUD showErrorWithStatus:@"该文件已下载"];
            return;
        }
        
        [SVProgressHUD showErrorWithStatus:saveError.localizedDescription];
    }
    
}

/**
 *  每次写入数据到临时文件时，就会调用一次这个方法。可在这里获得下载进度
 *
 *  @param bytesWritten              这次写入的文件大小
 *  @param totalBytesWritten         已经写入沙盒的文件大小
 *  @param totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

      didWriteData:(int64_t)bytesWritten

 totalBytesWritten:(int64_t)totalBytesWritten

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    NSLog(@"%@",[NSString stringWithFormat:@"下载进度:%f",(double)totalBytesWritten/totalBytesExpectedToWrite]);
    
    [SVProgressHUD showProgress:(double)totalBytesWritten/totalBytesExpectedToWrite];
    
}

/**
 *  恢复下载后调用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
}

@end
